/**
 * Copyright(C) 2008 Matthias Braunhofer
 * All rights reserved
 *
 * Created on: 26.07.2008
*/

package it.cums.editors;

import it.cums.actions.PrintAction;
import it.cums.controller.ApplicationController;
import it.cums.model.Country;
import it.cums.model.Supplier;
import it.cums.util.SupplierManager;

import java.util.List;

import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.ScrolledComposite;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IEditorSite;
import org.eclipse.ui.ISaveablePart2;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.actions.ActionFactory;
import org.eclipse.ui.part.EditorPart;

public class SupplierEditor extends EditorPart implements ISaveablePart2 {
	public static final String ID = "it.cums.editors.SupplierEditor";
	private Button saveButton;
	private Button closeButton;
	private Text nameText;
	private Label errorNameLabel;
	private Text referencePersonText;
	private Text taxNumberText;
	private Label errorTaxNumberLabel;
	private Text capText;
	private Label errorCapLabel;
	private Text locationText;
	private Label errorLocationLabel;
	private Text addressText;
	private Label errorAddressLabel;
	private Combo countryCombo;
	private Label errorCountryLabel;
	private Text phoneText;
	private Text mobilePhoneText;
	private Text emailText;
	private Text webSiteText;
	private Text accountDetailsText;
	private Text notesText;
	private Supplier supplier;
	private boolean changed = false;

	public SupplierEditor() {
		// TODO Auto-generated constructor stub
	}

	@Override
	public void doSave(IProgressMonitor monitor) {
		save();
		changed = false;
	}

	@Override
	public void doSaveAs() {
		// TODO Auto-generated method stub

	}

	@Override
	public void init(IEditorSite site, IEditorInput input)
			throws PartInitException {
		setSite(site);
		setInput(input);
		setPartName(input.getName());

		// Enabling the global print button
		PrintAction printAction = new PrintAction(((SupplierEditorInput)input).getSupplier());
        site.getActionBars().setGlobalActionHandler(ActionFactory.PRINT.getId(),printAction);
        
        supplier = ((SupplierEditorInput)input).getSupplier();
	}

	@Override
	public boolean isDirty() {
		// TODO Auto-generated method stub
		return changed;
	}

	@Override
	public boolean isSaveAsAllowed() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void createPartControl(Composite parent) {
		ScrolledComposite scrolledComposite = new ScrolledComposite(parent, SWT.V_SCROLL);
		Composite content = new Composite(scrolledComposite, SWT.NONE);
		content.setSize(500, 650);
		
		GridLayout layout = new GridLayout();
		layout.numColumns = 3;
		content.setLayout(layout);
		
		Composite container = new Composite(content, SWT.NONE);
		GridLayout containerLayout = new GridLayout();
		containerLayout.numColumns = 3;
		container.setLayout(containerLayout);
		saveButton = new Button(container, SWT.NONE);
		saveButton.setText("Save");
		saveButton.addSelectionListener(new SelectionListener() {
			@Override
			public void widgetDefaultSelected(SelectionEvent e) {
				// TODO Auto-generated method stub	
			}

			@Override
			public void widgetSelected(SelectionEvent e) {
				if (isUserInputValid()) {
					save();
					changed = false;
					firePropertyChange(EditorPart.PROP_DIRTY);
				}
			}});
		
		closeButton = new Button(container, SWT.NONE);
		closeButton.setText("Close");
		closeButton.addSelectionListener(new SelectionListener() {
			@Override
			public void widgetDefaultSelected(SelectionEvent e) {
				// TODO Auto-generated method stub	
			}

			@Override
			public void widgetSelected(SelectionEvent e) {
				IEditorPart current = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor();
				PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().closeEditor(current, true);
			}});
		
		GridData headerGrid = new GridData(GridData.FILL_HORIZONTAL);
		headerGrid.horizontalSpan = 3;
		headerGrid.verticalIndent = 15;
		
		Font boldFont = JFaceResources.getFontRegistry().getBold(JFaceResources.DEFAULT_FONT); 
		Label labelBasic = new Label(content, SWT.NONE);
		labelBasic.setText("Basic information");
		labelBasic.setFont(boldFont);
		labelBasic.setLayoutData(headerGrid);
		
		Label label1 = new Label(content, SWT.NONE);
		label1.setText("Supplier name:");
		GridData gd = new GridData(GridData.FILL_HORIZONTAL);
		nameText = new Text(content, SWT.BORDER | SWT.SINGLE);
		nameText.setLayoutData(gd);
		nameText.addModifyListener(new ModifyListener() {
			@Override
			public void modifyText(ModifyEvent arg0) {
				changed = true;
				if (getName().length() == 0) {
					errorNameLabel.setVisible(true);
				} else {
					errorNameLabel.setVisible(false);
				}
				setPartName(getName());
			}});
		errorNameLabel = new Label(content, SWT.NONE);
		errorNameLabel.setText("*");
		errorNameLabel.setVisible(false);
		
		Label label15 = new Label(content, SWT.NONE);
		label15.setText("Tax number:");
		taxNumberText = new Text(content, SWT.BORDER | SWT.SINGLE);
		taxNumberText.setLayoutData(gd);
		taxNumberText.addModifyListener(new ModifyListener() {
			@Override
			public void modifyText(ModifyEvent arg0) {
				changed = true;
				if (getTaxNumber().length() == 0) {
					errorTaxNumberLabel.setVisible(true);
				} else {
					errorTaxNumberLabel.setVisible(false);
				}
			}});
		errorTaxNumberLabel = new Label(content, SWT.NONE);
		errorTaxNumberLabel.setText("*");
		errorTaxNumberLabel.setVisible(false);
		
		Label label2 = new Label(content, SWT.NONE);
		label2.setText("Reference person:");
		referencePersonText = new Text(content, SWT.BORDER | SWT.SINGLE);
		referencePersonText.setLayoutData(gd);
		referencePersonText.addModifyListener(new ModifyListener() {
			@Override
			public void modifyText(ModifyEvent arg0) {
				changed = true;
			}});
		Label placeHolder = new Label(content, SWT.NONE);
		placeHolder.setText("");
		
		Label labelContact = new Label(content, SWT.NONE);
		labelContact.setText("Contact information");
		labelContact.setFont(boldFont);
		labelContact.setLayoutData(headerGrid);
		
		Label label3 = new Label(content, SWT.NONE);
		label3.setText("Address:");
		addressText = new Text(content, SWT.BORDER | SWT.SINGLE);
		addressText.setLayoutData(gd);
		addressText.addModifyListener(new ModifyListener() {
			@Override
			public void modifyText(ModifyEvent arg0) {
				changed = true;
				if (getAddress().length() == 0) {
					errorAddressLabel.setVisible(true);
				} else {
					errorAddressLabel.setVisible(false);
				}
			}});
		errorAddressLabel = new Label(content, SWT.NONE);
		errorAddressLabel.setText("*");
		errorAddressLabel.setVisible(false);
		
		Label label4 = new Label(content, SWT.NONE);
		label4.setText("CAP:");
		capText = new Text(content, SWT.BORDER | SWT.SINGLE);
		capText.setLayoutData(gd);
		capText.addModifyListener(new ModifyListener() {
			@Override
			public void modifyText(ModifyEvent arg0) {
				changed = true;
				if (getCap().length() == 0) {
					errorCapLabel.setVisible(true);
				} else {
					errorCapLabel.setVisible(false);
				}
			}});
		errorCapLabel = new Label(content, SWT.NONE);
		errorCapLabel.setText("*");
		errorCapLabel.setVisible(false);
		
		Label label5 = new Label(content, SWT.NONE);
		label5.setText("Location:");
		locationText = new Text(content, SWT.BORDER | SWT.SINGLE);
		locationText.setLayoutData(gd);
		locationText.addModifyListener(new ModifyListener() {
			@Override
			public void modifyText(ModifyEvent arg0) {
				changed = true;
				if (getLocation().length() == 0) {
					errorLocationLabel.setVisible(true);
				} else {
					errorLocationLabel.setVisible(false);
				}
			}});
		errorLocationLabel = new Label(content, SWT.NONE);
		errorLocationLabel.setText("*");
		errorLocationLabel.setVisible(false);
		
		Label label6 = new Label(content, SWT.NONE);
		label6.setText("Country:");
		countryCombo = new Combo(content, SWT.READ_ONLY);
		countryCombo.setLayoutData(gd);
		initCountries();
		countryCombo.addModifyListener(new ModifyListener() {
			@Override
			public void modifyText(ModifyEvent arg0) {
				changed = true;
				if (getCountry().length() == 0) {
					errorCountryLabel.setVisible(true);
				} else {
					errorCountryLabel.setVisible(false);
				}
			}});
		errorCountryLabel = new Label(content, SWT.NONE);
		errorCountryLabel.setText("*");
		errorCountryLabel.setVisible(false);
		
		Label label7 = new Label(content, SWT.NONE);
		label7.setText("Phone:");
		phoneText = new Text(content, SWT.BORDER | SWT.SINGLE);
		phoneText.setLayoutData(gd);
		phoneText.addModifyListener(new ModifyListener() {
			@Override
			public void modifyText(ModifyEvent arg0) {
				changed = true;
			}});
		placeHolder = new Label(content, SWT.NONE);
		placeHolder.setText("");
	
		Label label8 = new Label(content, SWT.NONE);
		label8.setText("Mobile phone:");
		mobilePhoneText = new Text(content, SWT.BORDER | SWT.SINGLE);
		mobilePhoneText.setLayoutData(gd);
		mobilePhoneText.addModifyListener(new ModifyListener() {
			@Override
			public void modifyText(ModifyEvent arg0) {
				changed = true;
			}});
		placeHolder = new Label(content, SWT.NONE);
		placeHolder.setText("");
		
		Label label9 = new Label(content, SWT.NONE);
		label9.setText("E-Mail:");
		emailText = new Text(content, SWT.BORDER | SWT.SINGLE);
		emailText.setLayoutData(gd);
		emailText.addModifyListener(new ModifyListener() {
			@Override
			public void modifyText(ModifyEvent arg0) {
				changed = true;
			}});
		placeHolder = new Label(content, SWT.NONE);
		placeHolder.setText("");
		
		Label label10 = new Label(content, SWT.NONE);
		label10.setText("Website:");
		webSiteText = new Text(content, SWT.BORDER | SWT.SINGLE);
		webSiteText.setLayoutData(gd);
		webSiteText.addModifyListener(new ModifyListener() {
			@Override
			public void modifyText(ModifyEvent arg0) {
				changed = true;
			}});
		placeHolder = new Label(content, SWT.NONE);
		placeHolder.setText("");
		
		Label labelAccountDetails = new Label(content, SWT.NONE);
		labelAccountDetails.setText("Account details");
		labelAccountDetails.setFont(boldFont);
		labelAccountDetails.setLayoutData(headerGrid);
		accountDetailsText = new Text(content, SWT.BORDER | SWT.MULTI);
		GridData gridData = new GridData(GridData.FILL_BOTH);
		gridData.horizontalSpan = 2;
		gridData.verticalSpan = 3;
		accountDetailsText.setLayoutData(gridData);
		accountDetailsText.addModifyListener(new ModifyListener() {
			@Override
			public void modifyText(ModifyEvent arg0) {
				changed = true;
			}});
		
		Label labelNotes = new Label(content, SWT.NONE);
		labelNotes.setText("Additional information");
		labelNotes.setFont(boldFont);
		labelNotes.setLayoutData(headerGrid);
		notesText = new Text(content, SWT.BORDER | SWT.MULTI);
		notesText.setLayoutData(gridData);
		notesText.addModifyListener(new ModifyListener() {
			@Override
			public void modifyText(ModifyEvent arg0) {
				changed = true;
			}});
		
		scrolledComposite.setContent(content);
		scrolledComposite.setExpandHorizontal(true);
		scrolledComposite.setExpandVertical(false);
		
		initialize();
	}
	
	private void initialize() {
		nameText.setText(supplier.getName());
		referencePersonText.setText(supplier.getReferencePerson());
		taxNumberText.setText(supplier.getTaxNumber());
		capText.setText(supplier.getCap());
		locationText.setText(supplier.getLocation());
		addressText.setText(supplier.getAddress());
		countryCombo.setText(supplier.getCountry().getDescription());
		phoneText.setText(supplier.getPhone());
		mobilePhoneText.setText(supplier.getMobilePhone());
		emailText.setText(supplier.getEmail());
		webSiteText.setText(supplier.getWebSite());
		accountDetailsText.setText(supplier.getAccountDetails());
		notesText.setText(supplier.getNotes());
		changed = false;
	}
	
	private void save() {
		SupplierManager.getInstance().updateSupplier(supplier, getName(), getReferencePerson(), getTaxNumber(), getAddress(), getCap(), getLocation(), 
													 getCountry(), getPhone(), getMobilePhone(), getEmail(), getWebsite(), getAccountDetails(), getNotes());
	}

	@Override
	public void setFocus() {
		// TODO Auto-generated method stub
	}
	
	@Override
	public void dispose() {
		super.dispose();
	}
	
	@Override
	public int promptToSaveOnClose() {
		MessageDialog dialog = new MessageDialog(getEditorSite().getShell(), 
												"Save resource", 
												null, 
												"'" + getTitle() + "' has been modified. Save changes?", 
												MessageDialog.QUESTION, 
												new String[] {
												IDialogConstants.YES_LABEL, 
												IDialogConstants.NO_LABEL, 
												IDialogConstants.CANCEL_LABEL},
												0);
		final int dialogResult = dialog.open();
		
		if (dialogResult == 0) {
			if (isUserInputValid()) {
				return ISaveablePart2.YES;
			} else {
				return ISaveablePart2.CANCEL;
			}
		} else if (dialogResult == 1) {
			return ISaveablePart2.NO;
		} else {
			return ISaveablePart2.CANCEL;
		}
	}

	
	private String getName() {
		return nameText.getText().trim();
	}
	
	private String getReferencePerson() {
		return referencePersonText.getText().trim();
	}
	
	private String getTaxNumber() {
		return taxNumberText.getText().trim();
	}
	
	private String getCap() {
		return capText.getText().trim();
	}
	
	private String getLocation() {
		return locationText.getText().trim();
	}
	
	private String getAddress() {
		return addressText.getText().trim();
	}
	
	private String getCountry() {
		return countryCombo.getText().trim();
	}
	
	private String getPhone() {
		return phoneText.getText().trim();
	}
	
	private String getMobilePhone() {
		return mobilePhoneText.getText().trim();
	}
	
	private String getEmail() {
		return emailText.getText().trim();
	}
	
	private String getWebsite() {
		return webSiteText.getText().trim();
	}
	
	private String getAccountDetails() {
		return accountDetailsText.getText().trim();
	}
	
	private String getNotes() {
		return notesText.getText().trim();
	}
	
	private boolean isUserInputValid() {
		if (getName().length() == 0) {
			return false;
		} else if (getTaxNumber().length() == 0) {
			return false;
		} else if (getAddress().length() == 0) {
			return false;
		} else if (getCap().length() == 0) {
			return false;
		} else if (getLocation().length() == 0) {
			return false;
		} else if (getCountry().length() == 0) {
			return false;
		}
		return true;
	}
	
	private void initCountries() {
		List<Country> countries = ApplicationController.getInstance().getCountries();
		for (Country country : countries) {
			countryCombo.add(country.getDescription());
		}
		countryCombo.add("", 0);
	}
}
